##########################################################################################

library(data.table)
library(optparse)

##########################################################################################

option_list <- list(
    make_option(c("--ibd_file"), type = "character") ,
    make_option(c("--out_path"), type = "character")
)

if(1!=1){
    
  ibd_file <- "~/20220915_gastric_multiple/dna_batch_raw/results/plink/Combine.genome.genome"
  out_path <- "~/20220915_gastric_multiple/dna_batch_raw/results/plink/"

}

###########################################################################################

parseobj <- OptionParser(option_list=option_list, usage = "usage: Rscript %prog [options]")
opt <- parse_args(parseobj)
print(opt)

ibd_file <- opt$ibd_file
out_path <- opt$out_path

###########################################################################################

dat_ibd <- data.frame(fread(ibd_file))
high_ibd <- dat_ibd[which(dat_ibd$PI_HAT>=0.5),]

result_ibd <- c()
for(sample in unique(c(dat_ibd$FID1,dat_ibd$FID2))){

  FID1 <- unique(high_ibd[which(high_ibd$FID1==sample | high_ibd$FID2==sample),'FID1'])
  FID2 <- unique(high_ibd[which(high_ibd$FID1==sample | high_ibd$FID2==sample),'FID2'])

  Gather_FID1 <- unique(high_ibd[which(high_ibd$FID1==sample | high_ibd$FID2==sample),'FID1'])
  Gather_FID2 <- unique(high_ibd[which(high_ibd$FID1==sample | high_ibd$FID2==sample),'FID2'])

  high_ibd_sample <- paste(unique(c(Gather_FID1,Gather_FID2)),collapse=",")

  ## 每个样本的IBD
  dat_fid <- unique(c(Gather_FID1,Gather_FID2))
  dat_Pi_Het <- c()
  for(fid in dat_fid){
    ## 样本自己的IBD=1
    print(fid)
    if(fid==sample){
      pi=1
    }else{
      pi <- round(high_ibd[which((high_ibd$FID1==sample & high_ibd$FID2==fid) | high_ibd$FID2==sample & high_ibd$FID1==fid ),'PI_HAT'],2)
    }
    dat_Pi_Het <- rbind(dat_Pi_Het,pi)
  }
  dat_Pi_Het <- paste(dat_Pi_Het,collapse=",")

  res_one <- data.frame(Sample=sample,IBD_realte=high_ibd_sample,PI_HAT=dat_Pi_Het)

  result_ibd <- rbind(result_ibd,res_one)
}

result_ibd <- result_ibd[order(result_ibd$IBD_realte),]

out_file <-paste(out_path,"/result_ibd.tsv",sep="")
write.table(result_ibd , out_file , row.names = F , sep = "\t" , quote = F)


